package com.example.controller;

import org.apache.commons.io.FileUtils;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.UUID;

@Controller
public class FileController {
    @GetMapping("/upload")
    public String upload(){
        return "upload";
    }
    @PostMapping("/upload")
    public String uploadFile(@RequestPart("file") MultipartFile file, Model model)  {
//        for(MultipartFile file : files){
            //如果文件为空，报错
            if(file.isEmpty()){
                model.addAttribute("msg","文件为空！！");
            }else{
                String dirPath = "D:/file/";
                File pathFile = new File(dirPath);
                //如果路径不存在，就创建相应的文件夹
                if(!pathFile.exists()){
                    pathFile.mkdirs();
                }
                String fileName = file.getOriginalFilename();
//        fileName = UUID.randomUUID()+"_"+fileName;

                File newFile = new File(dirPath+fileName);
                if(newFile.exists()){
                    model.addAttribute("msg","已有同名文件存在！！");
                    return "upload";
                }
                try{
                    file.transferTo(newFile);
                    model.addAttribute("msg","文件上传成功！！");
                }
                catch (Exception e){
                    model.addAttribute("msg","文件上传失败！！");
                }

            }
//        }

        return "error";

    }

    @GetMapping("/download")
    public String download(Model model){
        String dirPath = "D:/file/";
        File file = new File(dirPath);
        String[] files = file.list();
        model.addAttribute("files",files);
        return "download";
    }

    @GetMapping("/downloadfile")
//    @ResponseBody
    public ResponseEntity<byte[]> downloadfile(String filename) throws IOException {
        String dirPath = "D:/file/";
        File file = new File(dirPath+File.separator+filename);
        HttpHeaders httpHeaders = new HttpHeaders();
        httpHeaders.setContentDispositionFormData("attachment", URLEncoder.encode(filename,"UTF-8"));
        httpHeaders.setContentType(MediaType.APPLICATION_OCTET_STREAM);
        return new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(file),httpHeaders, HttpStatus.OK);
    }
}
